<template>
	<view v-if="refreshed">
        <image class="viewImage" :src="urlto" v-if="isImage" mode="widthFix"></image>
		<web-view :webview-styles="webviewStyles" :src="urlto"  class="iframepage" @message="onGetMessage" v-else></web-view>
	</view>
</template>

<script>
	import sceneMixins from '@/utils/sceneMixins';
	import {mapState, mapMutations} from 'vuex';
	export default {
		mixins: [sceneMixins],
		data() {
			return {
				urlto:'',
                isImage: true,
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				},
				refreshed: true
			
			}
		},
		onShow: function () {
			if (this.needRefresh) {
				this.refreshed = false;
				setTimeout(() => {
					this.refreshed = true;
				}, 200);
			}
		},
        onShareTimeline(options) {
			var vm = this;
			let routes = getCurrentPages();
			let route = routes[routes.length - 1];
			let curParam = route.options;
			var shareObj = {path: route.route, options: curParam};
            
			return {
				title: ' ',
				path: 'pages/index/index?share=' + encodeURIComponent(JSON.stringify(shareObj)),
				success(res) {
					uni.showToast({
					title: '分享成功'
					})
				},
				fail(res) {
					uni.showToast({
					title: '分享失败',
					icon: 'none'
					})
				}
			}
		},
		onShareAppMessage(options) {
			var vm = this;
			let routes = getCurrentPages();
			let route = routes[routes.length - 1];
			let curParam = route.options;
			var shareObj = {path: route.route, options: curParam};

			console.log('pages/index/index?share=' + encodeURIComponent(JSON.stringify(shareObj)));
			return {
				title: ' ',
				path: 'pages/index/index?share=' + encodeURIComponent(JSON.stringify(shareObj)),
				success(res) {
					uni.showToast({
					title: '分享成功'
					})
				},
				fail(res) {
					uni.showToast({
					title: '分享失败',
					icon: 'none'
					})
				}
			}
		},
		computed: {
			...mapState(['userInfo', 'globalConfig'])
		},
		onLoad(options) {
			var vm = this;
			if (options.title) {
				uni.setNavigationBarTitle({
					title: options.title
				});
				vm.title = options.title;
			}
	
            var url = decodeURIComponent(options.url);
			if (url.includes('needRefresh')) {
				vm.needRefresh = true;
			}
            vm.isImage = url.endsWith('.png');
			Promise.all([vm.doWxLogin(), vm.waitVariable('globalConfig')]).then(results => {
				var res = results[0];
				var config = results[1];
				url = url.replace('【openId】', res.openId)
				.replace('【token】', res.token)
				.replace('【timeStamp】', new Date().getTime())
				.replace('【lnglat】', vm.$store.state.lnglat)
				.replace('【USER_ID】', vm.userInfo ? vm.userInfo.userId : '')
				.replace('【userId】', vm.userInfo ? vm.userInfo.userId : '');

				if (config.isMultiSpace) {
					if (global.ipId && !url.includes('ipId=')) {
						url += vm.getLinkSign(url) + 'ipId=' + global.ipId;
					}
					if (!url.includes('openId=')) {
						url += vm.getLinkSign(url) + 'openId=' + res.openId;
					}
				}

                var defaultUrlPrefix = vm.API_PREFIX;
				// #ifdef MP-WEIXIN
                if (__wxConfig.envVersion != 'develop') {
                    defaultUrlPrefix = defaultUrlPrefix.replace(/:[1-9]\d*/, '');
                } else {
					if (global.localJSONConfigStarted == 'true' && !url.startsWith('/mobile')) {
						defaultUrlPrefix = 'http://localhost:8080';
					}
				}
				console.log((url.startsWith('http') ? '' : defaultUrlPrefix) + url);
				vm.urlto = (url.startsWith('http') ? '' : defaultUrlPrefix) + url;
				// #endif
				
				// #ifdef H5
				if (location.hostname != 'localhost') {
                    defaultUrlPrefix = defaultUrlPrefix.replace(/:[1-9]\d*/, '');
                }
				console.log(url);
				if (url.includes('needWebview')) {
					vm.urlto = url;
				} else {
					location.replace(url);
				}
				// #endif
               
			});
			
		},
		methods: {
			getLinkSign: function (url) {
				var fh = url.includes('?') ? '&' : '?';
                return url.endsWith(fh) ? '' : fh;
			},
			onGetMessage: function (data) {
				var vm = this;
				var val = data.detail.data[0];
				if (val && val.downloadbase64) {
					vm.saveImageToPhotosAlbum(val.downloadbase64);
				} else if (val && val.daohang) {
					uni.openLocation({
						...JSON.parse(val.daohang)
					});
				} else if (val && val.listPageNeedUpdate) {
					global.listPageNeedReload = true;
				} else if (val && val.doQrScan) {
					global.scanItem = val.doQrScan;
					vm.scanQrCode();
					uni.navigateTo({
						url: '/pages/openh5/index?title=' + (vm.title || '') + '&url=' + encodeURIComponent(vm.urlto)
					})
				} else if (val && val.previewDocument) {
					uni.showLoading();
					var filename = val.previewDocument;
					var documentUrl = (val.previewDocument.startsWith('/') ? vm.API_PREFIX : '') + val.previewDocument;
					let index = filename.lastIndexOf('.');
					var enfix = filename.substr(index + 1);
					var isImage = ['jpg', 'png', 'gif', 'jpeg'].includes(enfix);
					var isDoc = ['doc','docx','xls','xlsx','ppt','pptx','pdf'].includes(enfix);

					uni.downloadFile({
						url: documentUrl, 
						header: {'Cookie': uni.getStorageSync('loginCookie')},
						success: (res) => {
							uni.hideLoading();
							if (res.statusCode === 200) {
								// 使用uni.saveFile获取文件临时路径
								uni.saveFile({
									tempFilePath: res.tempFilePath,
									success: function (save) {
										if (isDoc) {
											uni.openDocument({
												filePath: save.savedFilePath,
												fileType: enfix,
												showMenu: true,
												success: function (open) {
													let res = wx.getSystemInfoSync();
													// if (res.platform != 'ios') {
														uni.navigateTo({
															url: '/pages/openh5/index?title=' + (vm.title || '') + '&url=' + encodeURIComponent(vm.urlto)
														})
													// }
												}
											})
										} else if (isImage) {
											uni.previewImage({
												urls: [save.savedFilePath],
												current: 0
											})
										}
									}
								})
							}
						}
					});
				} else if (val && val.toMiniApp) {
					uni.navigateToMiniProgram({
						appId: val.toMiniApp.appId,
						path: val.toMiniApp.path
					});
					uni.navigateTo({
						url: '/pages/openh5/index?title=' + (vm.title || '') + '&url=' + encodeURIComponent(vm.urlto)
					})
				}		
			},
			saveImageToPhotosAlbum(base64Str){
                var vm = this;
                let base64=base64Str.replace(/^data:image\/\w+;base64,/, "");//去掉data:image/png;base64,
                let filePath=wx.env.USER_DATA_PATH + '/' + vm.$Util.uuid() + '.png';
                uni.getFileSystemManager().writeFile({
                    filePath:filePath ,  //创建一个临时文件名
                    data: base64,    //写入的文本或二进制数据
                    encoding: 'base64',  //写入当前文件的字符编码
                    success: res => {
                        uni.saveImageToPhotosAlbum({
                            filePath: filePath,
                            success: function(res2) {
                                uni.showToast({
                                    title: '保存成功，请从相册选择再分享',
                                    icon:"none",
                                    duration:5000
                                })
								uni.navigateTo({
								    url: '/pages/openh5/index?title=' + vm.title + '&url=' + encodeURIComponent(vm.urlto)
								})
                            },
                            fail: function(err) {
                                // console.log(err.errMsg);
                            }
                        })
                    },
                    fail: err => {
                        //console.log(err)
                    }
                })
            }
        },
		
	}
</script>

<style lang="scss" scoped>
.viewImage {
    width: 750rpx;
}
</style>